#pragma once 
#include<iostream>
#include<cstring>
using namespace std;
#include<string>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<sys/types.h>
class TcpClient
{
    private:
      string svr_ip;
      int svr_port;
      int sock;
    public:
      TcpClient(string ip,int port)
        :svr_ip(ip)
        ,svr_port(port)
        ,sock(-1)
        {}
      void InitTcpClient()
      {
        sock=socket(AF_INET,SOCK_STREAM,0);
        if(sock<0)
        {
          cerr<<"socket error"<<endl;
          exit(2);
        }
      }
void Start()
      {
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family=AF_INET;
        peer.sin_port=htons(svr_port);
        peer.sin_addr.s_addr=inet_addr(svr_ip.c_str());
        if(connect(sock,(struct sockaddr*) &peer,sizeof(peer))==0)
        {
          //连接成功
          cout<<"connect success ..."<<endl;
          Request(sock);
        }
        else 
        {
          //连接失败
          cout<<"connect failed ..."<<endl;
        }
      }
      void Request(int sock)
      {
        string message;
        char buffer[1024];
        while(true)
        {
          cout<<"Please Enter# ";
          cin>>message;
          write(sock,message.c_str(),message.size());
          ssize_t n=read(sock,buffer,sizeof(buffer)-1);
          if(n>0)
          {
            buffer[n]=0;
          }
          cout<<"server echo# "<<buffer<<endl;
        }
      }
      ~TcpClient()
      {
        if(sock>=0)
        {
          close(sock);
        }
      }
      
};
